import { Component, OnInit } from '@angular/core';
import {Account} from "../account";
import {Router, ActivatedRoute} from "@angular/router";
import {ResponseUtil} from "../../../../util/response-util";
import {AccountsService} from "../accounts.service";
import {MsgResult} from "../../../../models/msg-result";
import {Path} from "../../../../portal/admin/admin-breadcrumb/breadcrumb";
import {PageSubject} from "../../../../util/page-subject";
import {OneDialogService} from "../../../../widgets/one-dialog/one-dialog.service";
import {FormGroup, Validators, FormBuilder} from "@angular/forms";
import {MsgConstants} from "../../../../constants/constants";

@Component({
  selector: 'app-account-update',
  templateUrl: './account-update.component.html'
})
export class AccountUpdateComponent implements OnInit {

  //声明实例
  account :Account;
  //定义变量id
  id: string;

  accountForm: FormGroup;

  constructor(
    private router : Router,
    private route : ActivatedRoute,
    private responseUtil : ResponseUtil,
    private pageSubject : PageSubject,
    private fb: FormBuilder,
    private dialogService : OneDialogService,
    private accountsService : AccountsService
  ) {
    this.initObject();
  }
  ngOnInit() {
    this.pushPage();
      //初始化表单
      this.initAccountFormData();
  }

  /**
   * 面包屑导航
   */
  private pushPage(){
    let path = new Path("权限系统","");
    this.pageSubject.pushPage("账户管理","修改",path);
  }


  /**
   * 构造表单
   */
  buildForm(): void {
    this.accountForm = this.fb.group({
      'id': [this.account.id],
      'accountName': [this.account.accountName, [
        Validators.required,
        Validators.maxLength(10),
        Validators.pattern(/^[A-Za-z0-9_]+$/)
      ]],
      'isEnable': [this.account.isEnable, [
        Validators.required,
        Validators.maxLength(1)
      ]],
      'isAudit': [this.account.isAudit, [
        Validators.required,
        Validators.maxLength(1)
      ]],
      'isAllowPc': [this.account.isAllowPc, [
        Validators.required,
        Validators.maxLength(1)
      ]],
      'isAllowApp': [this.account.isAllowApp, [
        Validators.required,
        Validators.maxLength(1)
      ]]
    });

    this.accountForm.valueChanges.subscribe(
      data => this.onValueChanged(data)
    );
    this.onValueChanged();
  }


  /**
   * 值变化监听
   * @param data
   */
  onValueChanged(data?: any) {
    if (!this.accountForm) {
      return;
    }
    const form = this.accountForm;
    for (const field in this.formErrors) {
      this.formErrors[field] = '';
      const control = form.get(field);
      if (control && control.dirty && !control.valid) {
        const messages = this.validationMessages[field];
        for (const key in control.errors) {
          this.formErrors[field] += messages[key] + ' ';
        }
      }
    }
  }

  /**
   * 校验字段
   * @type {{name: string; code: string}}
   */
  formErrors = {
    'accountName': '',
    'isEnable': '',
    'isAudit': '',
    'isAllowPc': '',
    'isAllowApp': '',
  };

  /**
   * 校验提示信息
   * @type {{name: {required: string; maxlength: string}; code: {required: string; maxlength: string; pattern: string}}}
   */
  validationMessages = {
    'accountName': {
      'required': '用户不能为空',
      'maxlength': '长度不能超过10',
      'pattern': '只能由字母、数字、下划线组成'
    }
  };



  /**
   * 初始化修改表单
   * @param id:账户id；this.processResult
   */
  initAccountFormData(){
    //获取路由参数
    let id = this.route.snapshot.params["accountId"];
    this.accountsService.getAccountById(id).subscribe(
      result=>this.responseUtil.success(result,this.processInitAccountResult),
      message =>this.responseUtil.error(message)
    );
  }

  /**
   * 获取初始化修改表单的数据
   * @param result
   */
  private processInitAccountResult = (result: MsgResult) => {
    if(result && result.code == MsgConstants.MSG_CODE_OK){
      this.account = result.data;

      console.log(JSON.stringify(this.account));

      this.accountForm.patchValue(this.account);
    }
    if(result && result.code != MsgConstants.MSG_CODE_OK){
      this.dialogService.info(result.message);
    }
  }

  /**
   * 实现修改功能
   */
  onSubmit(){
    this.account = this.accountForm.value;
    this.accountsService.updateAccount(this.account).subscribe(
      result=>this.responseUtil.success(result,this.processAccountUpdateResult),
      message =>this.responseUtil.error(message)
    );
  }

  /**
   * 获取修改日志
   * @param result
   */
  private processAccountUpdateResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.dialogService.modalSuccess(result.message, () => this.cancelAccountUpdate());
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 取消修改
   */
  cancelAccountUpdate() {
    this.router.navigate(['..'], {relativeTo: this.route});
  }

  /**
   * 实例化对象
   */
  private initObject(){
    this.account =new Account("","","","","","","","","","0","0","0","0","0");
    this.buildForm();
  }

}
